from django import forms
from utils.captcha.xtcaptcha import Captcha
import json
from utils import mbjson

class BaseForm(forms.Form):
    def get_error(self):
        errors=self.errors.as_json()
        error_dict = json.loads(errors)
        message =''
        for k ,v in error_dict.items():
            message = v[0].get('message',None)
        return message

    def get_error_response(self):
        if self.errors:
            return mbjson.json_params_error(message=self.get_error())
        else:
            return mbjson.json_result()


class LoginForm(BaseForm):
    username = forms.CharField(max_length=10,min_length=4)
    password = forms.CharField(max_length=20,min_length=6)
    captcha = forms.CharField(max_length=4,min_length=4)
    remember = forms.BooleanField(required=False)  #用户可能不会选择记住我

    def clean_captcha(self):
        captcha = self.cleaned_data.get('captcha',None)
        
        if Captcha.check_captcha(captcha):
            return captcha
        else:
            raise forms.ValidationError(u'验证码错误')





class UpdateProfileForm(BaseForm):
    avatar = forms.URLField(max_length=100,required=False)
    username = forms.CharField(max_length=10,min_length=4,required=False)


class UpdateEmailForm(BaseForm):
    email = forms.EmailField(required=True)

class AddCategoryForm(BaseForm):
    categoryname = forms.CharField(max_length=20)

class AddTagForm(BaseForm):
    tagname=forms.CharField(max_length=20)

class AddArticleForm(BaseForm):
    title = forms.CharField(max_length=20)
    category=forms.IntegerField(required=True)
    desc=forms.CharField(max_length=200,required=False)
    thumbnail= forms.URLField(max_length=100,required=False)
    content_html=forms.CharField()


class UpdateArticleForm(AddArticleForm):
    uid = forms.UUIDField()


class DeleteArticleForm(BaseForm):
    uid = forms.UUIDField(error_messages = {'required': u'文章id不能少'})

class TopArticleForm(BaseForm):
    uid = forms.UUIDField(error_messages={'required': u'文章id不能少'})

class CategoryForm(BaseForm):
    category_id = forms.IntegerField()

class EditCategoryForm(CategoryForm):
    name = forms.CharField()


